package com.demo.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.demo.common.constant.JWTConstants;

import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    public static final String SECRET = JWTConstants.JWT_SECRET;

    /**
     * 生成 token
     *
     * @param data
     * @return
     */
    public static String createJWT(Object data) {
        Map<String, Object> headers = new HashMap<>();
        headers.put(JWTConstants.JWT_ALG, JWTConstants.JWT_ALG_VALUE);
        headers.put(JWTConstants.JWT_TYP, JWTConstants.JWT_TYP_VALUE);
        return JWT.create()
                .withHeader(headers)
                .withClaim(JWTConstants.JWT_PAT_LOAD_KEY, JSONObject.toJSONString(data))
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证 token
     */
    public static Boolean verifyJWT(String jwtToken) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(jwtToken);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 解析 token
     */
    public static String parseJWT(String jwtToken) {
        return JWT.decode(jwtToken).getClaim(JWTConstants.JWT_PAT_LOAD_KEY).asString();
    }
}
